package com.atguigu.springcloud.controller;

import com.atguigu.springcloud.entitues.CommonResult;
import com.atguigu.springcloud.entitues.Payment;
import com.atguigu.springcloud.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author fxz
 * @date 2021/5/21 11:06
 **/
@RestController
@Slf4j
public class PaymentController {

    @Autowired
    private PaymentService paymentService;
    @Value("${server.port}")
    private String serverPort;
    @Autowired
    private DiscoveryClient discoveryClient;
    @PostMapping("/payment/create")
    public CommonResult<Payment> create(@RequestBody Payment payment) {
        int result = paymentService.create(payment);
        log.info("***" + result);
        log.info("---"+payment.getSerial());
        if (result > 0) {
            return new CommonResult(200, "插入数据库成功! 端口号:"+serverPort, result);
        } else {
            return new CommonResult(444, "插入数据库失败!", null);
        }
    }

    @GetMapping("/payment/get/{id}")
    public CommonResult getPaymentById(@PathVariable("id") Long id) {
        Payment payment = paymentService.getPaymentById(id);
        if (!ObjectUtils.isEmpty(payment)) {
            return new CommonResult(200, "查询成功! 端口号:"+serverPort, payment);
        } else {
            return new CommonResult(444, "查询结果为空!", null);
        }
    }

    @GetMapping("/payment/discovery")
    public Object discovery(){
        List<String> services = discoveryClient.getServices();
        services.forEach(item->
            log.info("---element:"+item)
        );
        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        instances.forEach(item->log.info(item.getInstanceId()+" "+item.getHost()+" "+item.getPort()+" "+item.getUri()));
        return discoveryClient;
    }

}
